import React, {useEffect} from "react";
import {createStyles} from "antd-style";
import FileDiveView from "@/pages/HomePage/FileDive/FileDiveView";
import FileDiveController from "@/pages/HomePage/FileDive/FileDiveController";
import {useFileDiveStore} from "@/pages/HomePage/FileDive/FileDiveStore.ts";
import FileApi from "@/api/web/FileApi.ts";
import {useSearchParams} from "react-router";

const userStyle = createStyles(({css, token}) => {
    return {
        container: css`
            height: auto;
            overflow-y: auto;

            &::-webkit-scrollbar {
                width: 2px;
            }

            &::-webkit-scrollbar-track {
                background-color: ${token.colorPrimaryBg};
            }

            &::-webkit-scrollbar-thumb {
                background-color: ${token.colorPrimary};
            }

            // 页面末尾站位

            &::after {
                content: "已经没有了";
                text-align: center;
                line-height: 50px;
                color: ${token.colorTextSecondary};
                display: block;
                height: 50px;
                margin: 10px;
                background: repeating-linear-gradient(
                        -45deg,
                        transparent,
                        transparent 10px,
                        ${token.colorBgContainer + "5f"} 10px,
                        ${token.colorBgContainer + "5f"} 20px
                );
            }
        `,
    }
})

let _abort: (() => void) | null = null

/**
 * 文件浏览
 */
const FileDive: React.FC = () => {
    const styles = userStyle().styles
    const [searchParams] = useSearchParams()
    let path = searchParams.get('path')
    if (path == null) path = '/'
    const {
        setContent,
        setTotal,
        setLoading,
        setPageCurrent,
        pageSize,
        pageCurrent,
    } = useFileDiveStore()

    useEffect(() => {
        // 重置分页（触发两次下面的effect影响不大）
        if (pageCurrent != 1) {
            setPageCurrent(1)
        }
    }, [path]);

    useEffect(() => {
        if (_abort != null) {
            _abort()
        }
        setLoading(true)
        const {abort, res} = FileApi.dirByPath(path, pageCurrent, pageSize)
        _abort = abort
        res.then(response => {
            setContent(response.data.records)
            setLoading(false)
            setTotal(response.data.total)
        }, reason => {
            setContent([])
            setLoading(false)
            setTotal(0)
        })
    }, [path, pageSize, pageCurrent]);

    return (
        <div className={styles.container}>
            <FileDiveController/>
            <FileDiveView/>
        </div>
    )
}

export default FileDive
